<?php
namespace App\Business\BLL;

use App\Business\IBLL\IPlay;
use App\Models\ChallengeGame;
use App\Models\Reservation;
use App\Models\Sect;
use Carbon\Carbon;

class SectBLL implements IPlay
{
    public $id;
    public $city;
    public $findId;

    public function __construct($findID)
    {
        $this->findId = $findID;
    }

    //挑战赛-A
    public function validateChallengeA()
    {
        if (!$this->verification()) {
            return ['status' => false, 'msg' => '未找到挑战者'];
        }

        if (!$this->hasGame()) {
            return ['status' => false, 'msg' => '存在未完成比赛'];
        }
        return ['status' => true, 'msg' => '验证通过'];
    }
    //挑战赛-B
    public function validateChallengeB()
    {
        if (!$this->verification()) {
            return ['status' => false, 'msg' => '未找到应战者'];
        }
        return ['status' => true, 'msg' => '验证通过'];
    }

    //预约-A
    public function validateReservationA($time)
    {
        if (!$this->verification()) {
            return ['status' => false, 'msg' => '未找到挑战者'];
        }

        if (!$this->hasReservation($time)) {
            return ['status' => false, 'msg' => '当天存在挑战'];
        }
        return ['status' => true, 'msg' => '验证通过'];
    }
    //预约-B
    public function validateReservationB()
    {
        if (!$this->verification()) {
            return ['status' => false, 'msg' => '未找到应战者'];
        }
        return ['status' => true, 'msg' => '验证通过'];
    }

    private function verification()
    {
        $play = Sect::where('id', $this->findId)
            ->first();
        if ($play && $play->status == 20) {
            $this->id = $play->id;
            $this->city = $play->city;
            return true;
        } else {
            return false;
        }
    }

    private function hasGame()
    {
        //查询是否有比赛
        $game = ChallengeGame::where([['status', 10], ['play_a', $this->id]])->first();
        if ($game) {
            return false;
        }
        return true;
    }

    private function hasReservation($time)
    {
        $time = Carbon::parse($time)->toDateString();
        $start = Carbon::parse($time)->toDateTimeString();
        $end = Carbon::parse($time . ' 23:59:59')->toDateTimeString();

        //查询当天是否存在挑战
        $game = Reservation::where('play_a', $this->id)
            ->whereIn('status', [10, 20])
            ->whereBetween('game_datetime', [$start, $end])
            ->first();
        if ($game) {
            return false;
        }
        return true;
    }
}
